package com.archive.manage.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.archive.common.constant.Operation_type;
import com.archive.common.core.domain.entity.SysUser;
import com.archive.common.core.domain.model.LoginUser;
import com.archive.common.utils.DateUtils;
import com.archive.common.utils.SecurityUtils;
import com.archive.common.utils.bean.BeanUtils;
import com.archive.manage.domain.Resume;
import com.archive.manage.domain.StuClassInfo;
import com.archive.manage.domain.Vo.StuArchiveVo;
import com.archive.manage.domain.entity.ArchiveCreateResponse;
import com.archive.manage.service.*;
import com.archive.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.archive.manage.mapper.StuArchiveMapper;
import com.archive.manage.domain.StuArchive;
import org.springframework.transaction.annotation.Transactional;

/**
 * 学生档案管理Service业务层处理
 *
 * @author marioduan
 * @date 2025-04-02
 */
@Service
public class StuArchiveServiceImpl implements IStuArchiveService {
    private IBlockchainService blockchainService = new BlockchainServiceImpl();
    @Autowired
    private StuArchiveMapper stuArchiveMapper;

    @Autowired
    private IArchiveLogService archiveLogService;
    @Autowired
    private IStuClassInfoService iStuClassInfoService;

    @Autowired
    private IResumeService iResumeService;

    @Autowired
    private ISkillCertificateService iSkillCertificateService;

    @Autowired
    private ISysUserService sysUserService;


    /**
     * 查询学生档案管理
     *
     * @param studentId 学生档案管理主键
     * @return 学生档案管理
     */
    @Override
    public StuArchive selectStuArchiveByStudentId(String studentId) {
        return stuArchiveMapper.selectStuArchiveByStudentId(studentId);
    }

    /**
     * 查询学生档案管理列表
     *
     * @param stuArchive 学生档案管理
     * @return 学生档案管理
     */
    @Override
    public List<StuArchive> selectStuArchiveList(StuArchive stuArchive) {
        return stuArchiveMapper.selectStuArchiveList(stuArchive);
    }

    /**
     * 新增学生档案管理
     *
     * @param stuArchiveVo 学生档案管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertStuArchive(StuArchiveVo stuArchiveVo) throws Exception {
        //添加学生档案信息
        stuArchiveVo.setCreateTime(DateUtils.getNowDate());
        stuArchiveVo.setUpdateTime(DateUtils.getNowDate());
        int result = stuArchiveMapper.insertStuArchive(stuArchiveVo);
        StuArchive stuArchive = new StuArchive();
        BeanUtils.copyProperties(stuArchiveVo, stuArchive);
        //学生档案上链
        //获取操作人
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String username = loginUser.getUsername();
        ArchiveCreateResponse archiveResp = blockchainService.createArchive("studentarchive", "channel3", "org1", username, stuArchive);
        String transactionID = archiveResp.getTransactionID();
        //添加班级信息
        StuClassInfo stuClassInfo = new StuClassInfo();
        stuClassInfo.setStudentId(stuArchiveVo.getStudentId());
        stuClassInfo.setClasse(stuArchiveVo.getClasse());
        stuClassInfo.setGrade(stuArchiveVo.getGrade());
        stuClassInfo.setMajorId(stuArchiveVo.getMajorId());
        iStuClassInfoService.insertStuClassInfo(stuClassInfo);
        //添加简历信息
        Resume resume = new Resume();
        BeanUtils.copyProperties(stuArchiveVo, resume);
        iResumeService.insertResume(resume);
        //添加职业技能证书
        if (stuArchiveVo.getCertificateName() != null && stuArchiveVo.getCertificateName().length > 0)
            iSkillCertificateService.insertSkillCertificate(stuArchiveVo.getStudentId(), stuArchiveVo.getCertificateName());

        //创建学生账号
        SysUser sysUser = new SysUser();
        sysUser.setUserName(stuArchive.getStudentId());
        sysUser.setNickName(stuArchive.getName());
        //密码默认学号后6位
        String studentId = stuArchive.getStudentId();
        String password = studentId.substring(studentId.length() - 6);
        sysUser.setRoleIds(new Long[]{100L}); //100-学生
        sysUser.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        sysUserService.insertUser(sysUser);

        //记录日志
        archiveLogService.archiveLog(stuArchiveVo, Operation_type.INSERT, transactionID);
        return result;
    }

    /**
     * 从Excel中批量新增学生档案
     *
     * @param stuArchiveList 学生档案管理
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public String batchInsertStuArchive(List<StuArchive> stuArchiveList) throws Exception {
        List<StuClassInfo> stuClassInfoList = new ArrayList<>();
        List<Resume> resumeList = new ArrayList<>();
        List<SysUser> usersList = new ArrayList<>();
        for (StuArchive stuArchive : stuArchiveList) {
            SysUser sysUser = new SysUser();
            sysUser.setUserName(stuArchive.getStudentId());
            sysUser.setNickName(stuArchive.getName());
            //密码默认学号后6位
            String studentId = stuArchive.getStudentId();
            String password = studentId.substring(studentId.length() - 6);
            sysUser.setPassword(password);
            usersList.add(sysUser);
            //男-0  女-1
            stuArchive.setGender("男".equals(stuArchive.getGender()) ? "0" : "1");
            String studentStatus = stuArchive.getStudentStatus();
            //在读-1 休学-2 退学-3 毕业-4
            if ("在读".equals(studentStatus))
                stuArchive.setStudentStatus("1");
            else if ("休学".equals(studentStatus))
                stuArchive.setStudentStatus("2");
            else if ("退学".equals(studentStatus))
                stuArchive.setStudentStatus("3");
            else if ("毕业".equals(studentStatus))
                stuArchive.setStudentStatus("4");
            //添加班级信息
            StuClassInfo stuClassInfo = new StuClassInfo();
            stuClassInfo.setStudentId(stuArchive.getStudentId());
//            stuClassInfo.setClasse();
//            stuClassInfo.setGrade();
//            stuClassInfo.setMajorId();
            stuClassInfoList.add(stuClassInfo);
            //添加简历信息
            Resume resume = new Resume();
            resume.setStudentId(stuArchive.getStudentId());
            //BeanUtils.copyProperties(stuArchiveVo,resume);
            resumeList.add(resume);
        }
        //批量插入档案
        int result = stuArchiveMapper.batchInsertStuArchive(stuArchiveList);
        //记录本地日志并循环上链
        archiveLogService.batchInsertArchiveLog(stuArchiveList, Operation_type.IMPORT);
        //批量新增班级信息
        iStuClassInfoService.batchInsertStuClassInfo(stuClassInfoList);
        //批量新增简历信息
        iResumeService.batchInsertResume(resumeList);
        //批量新增学生账号
        String operName = SecurityUtils.getLoginUser().getUsername();
        String msg = sysUserService.importUser(usersList, false, operName);
        //添加角色,先默认都是学生角色
        //使用stream流将usersList中的userid拿出来,组成一个新的数组
        Long[] userIds = usersList.stream().map(SysUser::getUserId).toArray(Long[]::new);
        sysUserService.insertUserAuthsToStudentRole(userIds);
        return msg;
    }

    /**
     * 修改学生档案管理
     *
     * @param stuArchiveVo 学生档案管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateStuArchive(StuArchiveVo stuArchiveVo) throws Exception {
        StuArchive stuArchive = new StuArchive();
        BeanUtils.copyProperties(stuArchiveVo, stuArchive);
        //修改档案上链
        String operator = SecurityUtils.getLoginUser().getUser().getUserName();
        ArchiveCreateResponse archiveResp = blockchainService.update("studentarchive", "channel3", "org1", operator, stuArchive);
        String transactionID = archiveResp.getTransactionID();
        //记录日志
        stuArchiveVo.setUpdateTime(DateUtils.getNowDate());
        archiveLogService.archiveLog(stuArchiveVo, Operation_type.UPDATE, transactionID);
        //班级信息表修改
        StuClassInfo stuClassInfo = new StuClassInfo();
        stuClassInfo.setStudentId(stuArchiveVo.getStudentId());
        stuClassInfo.setClasse(stuArchiveVo.getClasse());
        stuClassInfo.setGrade(stuArchiveVo.getGrade());
        stuClassInfo.setMajorId(stuArchiveVo.getMajorId());
        iStuClassInfoService.updateStuClassInfo(stuClassInfo);
        //学生简历表修改
        Resume resume = new Resume();
        String[] ignoreProperties = {"createTime", "createBy", "remark"};
        BeanUtils.copyProperties(stuArchiveVo, resume, ignoreProperties);
        iResumeService.updateResume(resume);
        //技能证书表修改
        iSkillCertificateService.deleteSkillCertificateByStudentId(stuArchiveVo.getStudentId());
        if (stuArchiveVo.getCertificateName().length > 0)
            iSkillCertificateService.insertSkillCertificate(stuArchiveVo.getStudentId(), stuArchiveVo.getCertificateName());
        return stuArchiveMapper.updateStuArchive(stuArchiveVo);
    }

    /**
     * 批量删除学生档案管理
     *
     * @param studentIds 需要删除的学生档案管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteStuArchiveByStudentIds(String[] studentIds) throws Exception {
        archiveLogService.batchDeleteArchiveLog(studentIds, Operation_type.DELETE);
        iStuClassInfoService.deleteStuClassInfoByStudentIds(studentIds);
        deleteSkillCertificateByStudentIds(studentIds);
        iResumeService.deleteResumeByStudentIds(studentIds);
        Long[] userIds = sysUserService.selectUserIdByStudentIds(studentIds);
        sysUserService.deleteStudentByIds(userIds);
        return stuArchiveMapper.deleteStuArchiveByStudentIds(studentIds);
    }

    /**
     * 删除学生档案管理信息
     *
     * @param studentId 学生档案管理主键
     * @return 结果
     */
    @Override
    public int deleteStuArchiveByStudentId(String studentId) {
        return stuArchiveMapper.deleteStuArchiveByStudentId(studentId);
    }

    private int deleteSkillCertificateByStudentIds(String[] studentIds) {
        return iSkillCertificateService.deleteSkillCertificateByStudentIds(studentIds);
    }
}
